package com.cjb.common.common.excel;

import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.cjb.common.exception.ServerException;
import com.cjb.common.util.Common;
import jakarta.servlet.http.HttpServletResponse;
import com.alibaba.excel.metadata.Sheet;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class export
 * @Date 2024-01-24 下午3:54
 */
public class ExcelUtil {
    /**
     * excel导出
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    public <T> void exportToExcel(List<T> dataList, Class<T> dataClass, HttpServletResponse response, String fileName,String sheetName) {
        // 对文件名进行UTF-8编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String excelName = URLUtil.encode(fileName).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + excelName + ".xlsx");

        /*
        *  HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easy excel没有关系
            String fileName = URLUtil.encode(excelName).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        * */
        // 创建 ExcelWriter 对象
        try (OutputStream outputStream = response.getOutputStream()) {
            ExcelWriter excelWriter = EasyExcel.write(outputStream, dataClass)
                    .excelType(ExcelTypeEnum.XLSX)
                    .build();

            // 创建 Sheet 对象，假设 sheet 名称为 "Sheet1"
            if (Common.isEmpty(sheetName) || sheetName.equals("")) {
                sheetName = "Sheet1";
            }

            // 确保sheetName也支持Unicode（如果需要）
            // 通常情况下，EasyExcel会自动处理，无需额外编码

            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(dataList, writeSheet);

            // 关闭 ExcelWriter，释放资源
            excelWriter.finish();
        } catch (IOException e) {
            throw new ServerException("文件导出异常: " + e.getMessage(), e);
        }
    }
}
